Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return[ [5,4,11,2], [5,8,4,5] ]

题目大意:给定一个二叉树和目标值,找出所有和等于目标值的根-叶路径

题目难度:Medium

import java.util.*;

/**
 * Created by gzdaijie on 16/6/9
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<>();
        ArrayList<Integer> tmp = new ArrayList<>();
        if (root != null) helper(result, tmp, root, sum);
        return result;
    }

    private void helper(List<List<Integer>> result, ArrayList<Integer> item, TreeNode root, int sum) {
        item.add(root.val);

        if (root.left == null && root.right == null) {
            if (sum == root.val) result.add((List<Integer>) item.clone());
            return;
        }

        if (root.left != null) {
            helper(result, item, root.left, sum - root.val);
            item.remove(item.size() - 1);
        }

        if (root.right != null) {
            helper(result, item, root.right, sum - root.val);
            item.remove(item.size() - 1);
        }
    }
}
gzdaijie            updated 2016-06-09 15:52:39

results matching ""

    No results matching ""